package com.marmot.cloud.framework.core.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class BaseController<T> {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // 绑定自定义解析器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, true));
        binder.registerCustomEditor(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));
    }

    /**
     * 初始化文件下载的 HttpHeaders
     *
     * @param fileName 文件名
     * @return HttpHeaders
     */
    protected HttpHeaders initFileDownloadHttpHeaders(String fileName) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.set("filename", fileName);
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
        return headers;
    }

    /**
     * 初始化文件上传的 HttpHeaders
     *
     * @return HttpHeaders
     */
    protected HttpHeaders initFileUploadHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        return headers;
    }

    /**
     * 设置跨域资源共享（CORS）头信息
     *
     * @return HttpHeaders
     */
    protected HttpHeaders initCORSHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS");
        headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Origin, Content-Type, Accept, Authorization");
        return headers;
    }

    /**
     * 设置 JSON 响应的 HttpHeaders
     *
     * @return HttpHeaders
     */
    protected HttpHeaders initJsonHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    /**
     * 文件上传处理
     *
     * @param file 上传的文件
     * @return 文件路径或其他信息
     */
    protected String handleFileUpload(MultipartFile file) {
        // 实现文件上传逻辑
        // 示例：保存文件并返回文件路径
        // 这里需要根据实际情况进行实现
        String filePath = "/uploaded/files/" + file.getOriginalFilename();
        // 假设文件保存成功，这里返回文件路径
        return filePath;
    }

    /**
     * 获取请求参数
     *
     * @param name 参数名称
     * @return 参数值
     */
    protected String getRequestParameter(String name) {
        return request.getParameter(name);
    }

    /**
     * 获取请求参数并转换为指定类型
     *
     * @param name 参数名称
     * @param clazz 参数类型
     * @param <T> 参数泛型
     * @return 转换后的参数值
     */
    protected <T> T getRequestParameter(String name, Class<T> clazz) {
        String value = request.getParameter(name);
        if (value == null) {
            return null;
        }
        if (clazz == Integer.class) {
            return clazz.cast(Integer.parseInt(value));
        } else if (clazz == Long.class) {
            return clazz.cast(Long.parseLong(value));
        } else if (clazz == Boolean.class) {
            return clazz.cast(Boolean.parseBoolean(value));
        } else if (clazz == Double.class) {
            return clazz.cast(Double.parseDouble(value));
        }
        return clazz.cast(value);
    }

    /**
     * 获取请求头信息
     *
     * @param name 头信息名称
     * @return 头信息值
     */
    protected String getRequestHeader(String name) {
        return request.getHeader(name);
    }

    /**
     * 获取客户端请求的 IP 地址
     *
     * @return IP 地址
     */
    protected String getClientIpAddress() {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 设置响应状态码
     *
     * @param status 状态码
     */
    protected void setResponseStatus(int status) {
        response.setStatus(status);
    }

    /**
     * 设置响应头信息
     *
     * @param name 头信息名称
     * @param value 头信息值
     */
    protected void setResponseHeader(String name, String value) {
        response.setHeader(name, value);
    }


    /**
     * 文件下载处理
     *
     * @param filePath 文件路径
     * @param fileName 文件名称
     * @param mimeType 文件类型
     *
     * @param response HttpServletResponse
     */
    protected void handleFileDownload(String filePath, String fileName, String mimeType, HttpServletResponse response) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                response.setContentLengthLong(file.length());
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                inputStream.close();
                outputStream.flush();
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            }
        } catch (IOException e) {
            throw new RuntimeException("File download failed", e);
        }
    }



    /**
     * 获取请求的完整 URL
     *
     * @return 完整 URL
     */
    protected String getRequestURL() {
        StringBuilder url = new StringBuilder(request.getRequestURL());
        String queryString = request.getQueryString();
        if (queryString != null) {
            url.append("?").append(queryString);
        }
        return url.toString();
    }

    // ==================================private===================================
}
